package com.harmontronics.hanma.paas.paas.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.harmontronics.hanma.paas.paas.annotation.TokenValidSkip;
import com.harmontronics.hanma.paas.paas.common.PageBase;
import com.harmontronics.hanma.paas.paas.common.ResponseEntity;
import com.harmontronics.hanma.paas.paas.domain.iam.entity.HmMenu;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.*;
import com.harmontronics.hanma.paas.paas.domain.organization.entity.valueobject.I18nKeyEnum;
import com.harmontronics.hanma.paas.paas.domain.organization.repository.po.HmUserPO;
import com.harmontronics.hanma.paas.paas.dto.organization.input.*;
import com.harmontronics.hanma.paas.paas.dto.organization.output.HmUserResult;
import com.harmontronics.hanma.paas.paas.exception.ErrorKeyException;
import com.harmontronics.hanma.paas.paas.service.HmUserExportAppService;
import com.harmontronics.hanma.paas.paas.service.HmUserImportAppService;
import com.harmontronics.hanma.paas.paas.domain.organization.service.IHmUserService;
import com.harmontronics.hanma.paas.paas.utils.FileUtil;
import com.harmontronics.hanma.paas.paas.utils.ParamUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 用户表
 *
 * @author paas-generator
 * @email paas-generator@harmontronics.com
 * @date 2021-04-01 14:45:15
 */
@RestController
@RequestMapping("/api/hmuser")
@Api(tags = {"用户表"})
public class HmUserController {

    @Autowired
    private IHmUserService hmUserappService;

    @Autowired
    private HmUserImportAppService hmUserImportAppService;

    @Autowired
    private HmUserExportAppService hmUserExportAppService;

    @Value("${mos.oss.enabled:false}")
    private Boolean mosEnabled;

    /**
     * 列表
     */
    @GetMapping("/list")
    @ApiOperation("列表")
    public ResponseEntity<List<HmUserResult>> list() {
        List<HmUser> hmUserList = hmUserappService.getList();

        return ResponseEntity.ok(Convert.toList(HmUserResult.class, hmUserList));
    }

    @GetMapping("/page/list")
    @ApiOperation(value = "获取所有User")
    public ResponseEntity<PageBase<HmUserResult>> list(
            @RequestParam int pageNo,
            @RequestParam int pageSize,
            @RequestParam(required = false) Long orgId,
            @RequestParam(required = false, defaultValue = "") String name,
            @RequestParam(required = false) String jobNumber,
            @RequestParam(required = false) String mobile,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) String username) {
        PageBase<HmUser> hmUserPageBase = hmUserappService.getPageUserWithParams(pageNo,pageSize, orgId, name, jobNumber, status, email, mobile, username);
        PageBase<HmUserResult> resultPageBase = PageBase.copy(hmUserPageBase, HmUserResult.class);
        return ResponseEntity.ok(resultPageBase);
    }

    @GetMapping("/search")
    @ApiOperation(value = "获取所有User")
    public ResponseEntity<PageBase<HmUserResult>> list(
            @RequestParam int pageNo,
            @RequestParam int pageSize,
            @RequestParam String searchKey) {
        PageBase<HmUserPO> hmUserPageBase = hmUserappService.getPageUserWithParams(pageNo,pageSize, searchKey);
        PageBase<HmUserResult> resultPageBase = PageBase.copy(hmUserPageBase, HmUserResult.class);
        return ResponseEntity.ok(resultPageBase);
    }


    /**
     * 信息
     */
    @GetMapping("/info")
    @ApiOperation("详情")
    public ResponseEntity<HmUserResult> info(@RequestParam Long id) {
        HmUser hmUser = hmUserappService.get(id);
        HmUserResult result = BeanUtil.toBean(hmUser, HmUserResult.class);
        return ResponseEntity.ok(result);
    }

    /**
     * 保存
     */
    @PostMapping()
    @ApiOperation("保存")
    public ResponseEntity<Long> save(@Valid @RequestBody HmUserCreateInput hmUserInput, BindingResult bindingResult) {
        ParamUtils.valid(bindingResult);
        HmUser hmUser = BeanUtil.toBean(hmUserInput, HmUser.class);
        Long userId = hmUserappService.save(hmUser);

        return ResponseEntity.ok(userId);
    }

    /**
     * 修改
     */
    @PutMapping
    @ApiOperation("修改")
    public ResponseEntity<String> update(@Valid @RequestBody HmUserUpdateInput hmUserInput, BindingResult bindingResult) {
        ParamUtils.valid(bindingResult);
        HmUser hmUser = BeanUtil.toBean(hmUserInput, HmUser.class);
        hmUserappService.update(hmUser);
        return ResponseEntity.ok();
    }

    /**
     * 删除
     */
    @DeleteMapping()
    @ApiOperation("删除")
    public ResponseEntity<String> delete(@RequestBody Long[] ids) {
        hmUserappService.remove(Arrays.asList(ids));

        return ResponseEntity.ok();
    }

    @GetMapping("/validate-field")
    @ApiOperation(value = "邮箱 手机 HID 工号唯一性检验")
    public ResponseEntity<String> uniqueCheck(
            @RequestParam(required = false) Long id,
            @RequestParam String key,
            @RequestParam String value) {
        //field字段用驼峰
        hmUserappService.uniqueCheck(id, key, value);
        return ResponseEntity.ok();
    }

    @PutMapping("move-org")
    @ApiOperation(value = "批量移动用户")
    public ResponseEntity<String> moveOrg(@RequestBody UserMoveOrgInPut moveOrg) {
        UserMoveOrg userMoveOrg = BeanUtil.toBean(moveOrg, UserMoveOrg.class);
        hmUserappService.moveOrg(userMoveOrg);
        return ResponseEntity.ok();
    }

    @PutMapping("quit")
    @ApiOperation(value = "批量离职用户")
    public ResponseEntity<String> quit(@RequestBody UserMoveOrgInPut moveOrgDto) {
        hmUserappService.quit(moveOrgDto.getIds());
        return ResponseEntity.ok();
    }

    @PutMapping("sort")
    @ApiOperation(value = "排序用户")
    public ResponseEntity<String> sort(@RequestBody UserSortInput userSortInput) {
        UserSort userSort = BeanUtil.toBean(userSortInput, UserSort.class);
        hmUserappService.userSort(userSort);
        return ResponseEntity.ok();
    }

    @GetMapping("export")
    @ApiOperation(value = "导出组织用户")
    @TokenValidSkip
    public void exportUser(
            @RequestParam long orgId,
            @RequestParam(required = false, defaultValue = "") String name,
            @RequestParam(required = false) String jobNumber,
            @RequestParam(required = false) String mobile,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) String username,
            HttpServletRequest request,
            HttpServletResponse response) {
        try {
            hmUserExportAppService.exportUser(orgId, name, username, mobile, status, email, request, response);
        } catch (IOException e) {
            throw new ErrorKeyException(I18nKeyEnum.EXPORT_FILE_NOT_EXIST);
        }
    }

    @PostMapping("import")
    @ApiOperation(value = "导入组织用户")
    public ResponseEntity<Map<String, Object>> importUser(MultipartFile file, @RequestParam long orgId, @RequestParam Boolean confirm) throws Exception {
        File file2 = FileUtil.multipartFileToFile(file);
        return ResponseEntity.ok(hmUserImportAppService.importExcelUser(file2, orgId, confirm));
    }

    @PostMapping("login")
    @ApiOperation(value = "用户登录")
    @TokenValidSkip
    public ResponseEntity login(@RequestBody HmUserLoginInput userLogin) {
        HmUser hmUser = BeanUtil.toBean(userLogin, HmUser.class);
        return ResponseEntity.ok(hmUserappService.login(hmUser));
    }


    @DeleteMapping("logout")
    @ApiOperation(value = "退出登录")
    @TokenValidSkip
    public ResponseEntity logout(HttpServletRequest request) {
        hmUserappService.logout();
        return ResponseEntity.ok();
    }

    @PutMapping(value = "changePwd")
    @ApiOperation("修改密码")
    public ResponseEntity changePassword(@RequestBody ChangePasswordInput changePasswordInputDto) {

        ChangePassword changePassword = BeanUtil.toBean(changePasswordInputDto, ChangePassword.class);
        hmUserappService.changePassword(changePassword);
        return ResponseEntity.ok();
    }

    @PutMapping("reset-psd")
    @ApiOperation(value = "批量重置密码")
    public ResponseEntity resetPassword(@RequestBody Long[] ids) {
        hmUserappService.resetPassword(Arrays.asList(ids));
        return ResponseEntity.ok();
    }

    /**
     * 信息
     */
    @GetMapping("/auth")
    @ApiOperation("用户权限列表")
    public ResponseEntity<List<HmMenu>> auth() {
        List<HmMenu> menuList = hmUserappService.getAuthWithUserId();
        return ResponseEntity.ok(menuList);
    }

    @GetMapping("/user-by-ids")
    @ApiOperation("用户列表")
    public ResponseEntity<List<HmUser>> findByIds(@RequestParam String ids) {
        List<Long> idList = Arrays.asList(ids.split(",")).stream()
                .map(id -> Long.parseLong(id)).collect(Collectors.toList());
        return ResponseEntity.ok(hmUserappService.getUsersByIds(idList));
    }

    @GetMapping("/user-by-token")
    @ApiOperation("appToken获取用户")
    public ResponseEntity<HmUser> findByToken() {

        return ResponseEntity.ok(hmUserappService.getUserWithToken());

    }

    @PutMapping("/update-pwd")
    @ApiOperation(value = "更新密码")
    public ResponseEntity updatePassword(@RequestBody HmUserPwdUpdateInput hmUserPwdUpdateInput) {
        HmUserPwd hmUserPwd = BeanUtil.toBean(hmUserPwdUpdateInput, HmUserPwd.class);
        hmUserappService.updatePassword(hmUserPwd);
        return ResponseEntity.ok();
    }

    @PutMapping("/reset-higher")
    @ApiOperation(value = "批量更新主部门")
    public ResponseEntity updateHigher(@RequestBody HmUserHigherUpdateInput hmUserHigherUpdateInput) {
        HmUserHigherUpdate hmUserHigher = BeanUtil.toBean(hmUserHigherUpdateInput, HmUserHigherUpdate.class);
        hmUserappService.updateHigher(hmUserHigher);
        return ResponseEntity.ok();
    }

    @GetMapping("/download-excel")
    @ApiOperation(value = "下载导入模板")
    public void downloadExcel(HttpServletRequest request, HttpServletResponse response) {
        try {
            hmUserExportAppService.downloadExcel(request, response);
        } catch (IOException e) {
            throw new ErrorKeyException(I18nKeyEnum.EXPORT_FILE_NOT_EXIST);
        }
    }

    @GetMapping("/mos-enabled")
    @ApiOperation("部署方式")
    @TokenValidSkip
    public ResponseEntity<Boolean> getDeploymentWay(){
        return ResponseEntity.ok(mosEnabled);
    }


}
